<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Android," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="当Android的View测量完毕之后，才可以去布局。我们在测量时获取到的MeasuredHeight和MeasuredWidth,在布局的时候就会用到，毕竟只有知道尺寸才好确定位置。">
<meta property="og:type" content="article">
<meta property="og:title" content="Android View的布局过程">
<meta property="og:url" content="https://www.yanhaoblog.com/2017/01/21/Android-View的布局过程/index.html">
<meta property="og:site_name" content="闫浩的博客">
<meta property="og:description" content="当Android的View测量完毕之后，才可以去布局。我们在测量时获取到的MeasuredHeight和MeasuredWidth,在布局的时候就会用到，毕竟只有知道尺寸才好确定位置。">
<meta property="og:updated_time" content="2017-01-21T05:21:17.255Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android View的布局过程">
<meta name="twitter:description" content="当Android的View测量完毕之后，才可以去布局。我们在测量时获取到的MeasuredHeight和MeasuredWidth,在布局的时候就会用到，毕竟只有知道尺寸才好确定位置。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.yanhaoblog.com/2017/01/21/Android-View的布局过程/"/>





  <title> Android View的布局过程 | 闫浩的博客 </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">闫浩的博客</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
    
      <p class="site-subtitle">Sometimes you got to run before you can walk</p>
    
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="https://www.yanhaoblog.com/2017/01/21/Android-View的布局过程/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="闫浩">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/images/demo.png">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="闫浩的博客">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="闫浩的博客" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                Android View的布局过程
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2017-01-21T13:08:15+08:00">
                2017-01-21
              </time>
            

            

            
          </span>

          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2017/01/21/Android-View的布局过程/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="2017/01/21/Android-View的布局过程/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>当Android的View测量完毕之后，才可以去布局。我们在测量时获取到的<code>MeasuredHeight</code>和<code>MeasuredWidth</code>,在布局的时候就会用到，毕竟只有知道尺寸才好确定位置。<br><a id="more"></a><br>布局相对于测量来说就相对简单了很多。布局的过程就是确定View在界面显示位置的过程。View是一个矩形，决定一个View在界面显示的位置的信息主要是四个边到父View的边距，这里会有四个变量来记录各个边到父View的距离：</p>
<ul>
<li>mLeft:View左边缘距离父View左部边缘的距离</li>
<li>mTop:View上边缘距离父View上部边缘的距离</li>
<li>mBottom:View底边缘距离父View上部边缘的距离</li>
<li>mRight:View右边缘距离父View左部边缘的距离</li>
</ul>
<blockquote>
<p> 注意:这里的距离单位是像素;Android 屏幕的像素原点在屏幕的左上角，所以View的宽高计算如下:</p>
<p> View的宽=mRight-mLeft<br> View的高=mBottom-mTop</p>
</blockquote>
<p>这里的宽高和测量来的MeasuredWidth和MeasuredHeight是不同的，不要混淆.看它们的源码：</p>
<p>测量得到的高</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">getMeasuredHeight</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> mMeasuredHeight &amp; MEASURED_SIZE_MASK;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>View实际的高</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">int</span> <span class="title">getHeight</span><span class="params">()</span> </span>&#123;</div><div class="line">    <span class="keyword">return</span> mBottom - mTop;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>width和MeasuredWidth代码跟上面的代码类似就不在贴了。</p>
<p>布局是绘制的前提，只有布局完毕才可以去绘制。View布局时调用的方法是<code>layout(int l, int t, int r, int b)</code>它的是个参数就是代表View四个边距离父View的距离。虽然View了layout 方法，但是不提倡去重写它，如果有需要我们应该去重写 <code>onLayout(boolean changed, int left, int top, int right, int bottom)</code>,我们先看一下layout方法：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">layout</span><span class="params">(<span class="keyword">int</span> l, <span class="keyword">int</span> t, <span class="keyword">int</span> r, <span class="keyword">int</span> b)</span> </span>&#123;</div><div class="line">  	<span class="comment">//判断onMeasure是否应该跳过,(变量mPrivateFlags3存着一些关于Layout的信息，应该是用来判断View是否测量过，具体的没研究过)</span></div><div class="line">    <span class="keyword">if</span> ((mPrivateFlags3 &amp; PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != <span class="number">0</span>) &#123;</div><div class="line">        onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);</div><div class="line">        mPrivateFlags3 &amp;= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">int</span> oldL = mLeft;</div><div class="line">    <span class="keyword">int</span> oldT = mTop;</div><div class="line">    <span class="keyword">int</span> oldB = mBottom;</div><div class="line">    <span class="keyword">int</span> oldR = mRight;</div><div class="line">  	<span class="comment">//根据布局模式来判断是调用setOpticalFrame还是setFrame；</span></div><div class="line">  	<span class="comment">//setOpticalFrame内部也会再次调用setFrame,所以不论isLayoutModeOptical是false还是true，都会调用setFrame</span></div><div class="line">	<span class="comment">//setFrame用来分配View的位置和大小，如果新传入的位置和尺寸与之前的位置和尺寸有差别就会返回true。</span></div><div class="line">	<span class="comment">//所以这里获取的是View的位置或者尺寸是否发生变化</span></div><div class="line">    <span class="keyword">boolean</span> changed = isLayoutModeOptical(mParent) ?</div><div class="line">            setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);</div><div class="line">    <span class="keyword">if</span> (changed || (mPrivateFlags &amp; PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) &#123;</div><div class="line">      	<span class="comment">//如果View的位置或者尺寸发生变化或者满足(mPrivateFlags &amp; PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED,就会首先调用onLayout</span></div><div class="line">      	<span class="comment">//onLayout是空的，没有任何实现，需要我们自己去实现。</span></div><div class="line">      	<span class="comment">//凡是继承ViewGroup的类一般都要重写这方法，来确定其中的子view的位置和尺寸</span></div><div class="line">        onLayout(changed, l, t, r, b);</div><div class="line">        mPrivateFlags &amp;= ~PFLAG_LAYOUT_REQUIRED;</div><div class="line">		<span class="comment">//这里设置 OnLayoutChangeListener 监听事件</span></div><div class="line">      	<span class="comment">//ListenerInfo里面专门有个ArrayList来存储OnLayoutChangeListener</span></div><div class="line">        ListenerInfo li = mListenerInfo;</div><div class="line">        <span class="keyword">if</span> (li != <span class="keyword">null</span> &amp;&amp; li.mOnLayoutChangeListeners != <span class="keyword">null</span>) &#123;</div><div class="line">          	<span class="comment">//对ArrayList中的OnLayoutChangeListener中的事件监听器进行克隆</span></div><div class="line">            ArrayList&lt;OnLayoutChangeListener&gt; listenersCopy =</div><div class="line"> (ArrayList&lt;OnLayoutChangeListener&gt;)li.mOnLayoutChangeListeners.clone();</div><div class="line">            <span class="keyword">int</span> numListeners = listenersCopy.size();</div><div class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; numListeners; ++i) &#123;</div><div class="line">              <span class="comment">//遍历添加进来的事件监听器，依次调用onLayoutChange方法；这样layout就能在收到布局发生变化时得到响应了</span></div><div class="line">                listenersCopy.get(i).onLayoutChange(<span class="keyword">this</span>, l, t, r, b, oldL, oldT, oldR, oldB);</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">    mPrivateFlags &amp;= ~PFLAG_FORCE_LAYOUT;</div><div class="line">    mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><code>onLayout(boolean changed, int left, int top, int right, int bottom)</code>方法很简单，首先会判断一下是需要测量一下，如果不需要，记录一下传入的四个边到父View的边距;然后判断View的尺寸和位置是否变化过，如果变化去就调用onLayout方法，并且遍历OnLayoutChangedListener监听器。</p>
<p><code>onLayout(boolean changed, int left, int top, int right, int bottom)</code>这个方法是空的，是需要子类去重写的。它的主要作用就是确定该View中子view的位置。通常会遍历该View中所有的子view，然后依次调用子view的layout方法，来确定子View的位置和尺寸。我们看一下FrameLayout中部分代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="meta">@Override</span></div><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onLayout</span><span class="params">(<span class="keyword">boolean</span> changed, <span class="keyword">int</span> left, <span class="keyword">int</span> top, <span class="keyword">int</span> right, <span class="keyword">int</span> bottom)</span> </span>&#123;</div><div class="line">    layoutChildren(left, top, right, bottom, <span class="keyword">false</span> <span class="comment">/* no force left gravity */</span>);</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">void</span> <span class="title">layoutChildren</span><span class="params">(<span class="keyword">int</span> left, <span class="keyword">int</span> top, <span class="keyword">int</span> right, <span class="keyword">int</span> bottom, <span class="keyword">boolean</span> forceLeftGravity)</span> </span>&#123;</div><div class="line">  	<span class="comment">//获取子View的个数</span></div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> count = getChildCount();</div><div class="line">	<span class="comment">//获取父View的四边</span></div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> parentLeft = getPaddingLeftWithForeground();</div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> parentRight = right - left - getPaddingRightWithForeground();</div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> parentTop = getPaddingTopWithForeground();</div><div class="line">    <span class="keyword">final</span> <span class="keyword">int</span> parentBottom = bottom - top - getPaddingBottomWithForeground();</div><div class="line">	<span class="comment">//遍历所有的子view</span></div><div class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; count; i++) &#123;</div><div class="line">        <span class="keyword">final</span> View child = getChildAt(i);</div><div class="line">      	<span class="comment">//只有在子view可见并且不占据位置的时候才去设置子view的尺寸和位置</span></div><div class="line">        <span class="keyword">if</span> (child.getVisibility() != GONE) &#123;</div><div class="line">			<span class="comment">//……省略子View在各个Gravity情况下四边距离屏幕边距的数值……</span></div><div class="line">            child.layout(childLeft, childTop, childLeft + width, childTop + height);</div><div class="line">        &#125;</div><div class="line">    &#125;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>所以我们在继承ViewGroup时，重写onLayout方法也可以做类似的处理。</p>
<p>​    在上面我们提到布局变化监听，其实在View里提供了一个<code>onSizeChanged(newWidth, newHeight, oldWidth, oldHeight)</code>；当View的尺寸发生变化时就会调用这个方法。不过它刚加入的View树中时，它使用还之前的尺寸，都是0。</p>
<p>​    在源码里，它是在 <code>setFrame(int left, int top, int right, int bottom)</code>中调用的。上面提到了setFrame是用来分配View的位置和大小，如果新传入的位置和尺寸与之前的位置和尺寸有差别就会返回true。简单看一下setFrame调用onSizeChanged的过程：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">boolean</span> <span class="title">setFrame</span><span class="params">(<span class="keyword">int</span> left, <span class="keyword">int</span> top, <span class="keyword">int</span> right, <span class="keyword">int</span> bottom)</span> </span>&#123;</div><div class="line">    <span class="keyword">boolean</span> changed = <span class="keyword">false</span>;</div><div class="line">	<span class="comment">//……省略log</span></div><div class="line">	<span class="comment">//新传入边距跟之前记录的边距不同，就说明View的尺寸或者位置发生变化</span></div><div class="line">    <span class="keyword">if</span> (mLeft != left || mRight != right || mTop != top || mBottom != bottom) &#123;</div><div class="line">        changed = <span class="keyword">true</span>;</div><div class="line">      </div><div class="line">        <span class="keyword">int</span> drawn = mPrivateFlags &amp; PFLAG_DRAWN;</div><div class="line">        <span class="keyword">int</span> oldWidth = mRight - mLeft;</div><div class="line">        <span class="keyword">int</span> oldHeight = mBottom - mTop;</div><div class="line">        <span class="keyword">int</span> newWidth = right - left;</div><div class="line">        <span class="keyword">int</span> newHeight = bottom - top;</div><div class="line">      	<span class="comment">//根据新边距和旧边距，判断尺寸是否发生变化</span></div><div class="line">        <span class="keyword">boolean</span> sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);</div><div class="line">		<span class="comment">//重新绘图</span></div><div class="line">        invalidate(sizeChanged);</div><div class="line">		<span class="comment">//将新边距赋值</span></div><div class="line">        mLeft = left;</div><div class="line">        mTop = top;</div><div class="line">        mRight = right;</div><div class="line">        mBottom = bottom;</div><div class="line">        mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);</div><div class="line">        mPrivateFlags |= PFLAG_HAS_BOUNDS;</div><div class="line">      	<span class="comment">//如果尺寸发生变化就会调用sizeChange，onSizeChanged就是在sizeChange方法里调用的</span></div><div class="line">        <span class="keyword">if</span> (sizeChanged) &#123;</div><div class="line">            sizeChange(newWidth, newHeight, oldWidth, oldHeight);</div><div class="line">        &#125;</div><div class="line">        <span class="keyword">if</span> ((mViewFlags &amp; VISIBILITY_MASK) == VISIBLE || mGhostView != <span class="keyword">null</span>) &#123;</div><div class="line">            mPrivateFlags |= PFLAG_DRAWN;</div><div class="line">            invalidate(sizeChanged);</div><div class="line">            invalidateParentCaches();</div><div class="line">        &#125;</div><div class="line">        mPrivateFlags |= drawn;</div><div class="line">        mBackgroundSizeChanged = <span class="keyword">true</span>;</div><div class="line">        <span class="keyword">if</span> (mForegroundInfo != <span class="keyword">null</span>) &#123;</div><div class="line">            mForegroundInfo.mBoundsChanged = <span class="keyword">true</span>;</div><div class="line">        &#125;</div><div class="line">        notifySubtreeAccessibilityStateChangedIfNeeded();</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">return</span> changed;</div><div class="line">&#125;</div><div class="line"></div><div class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">sizeChange</span><span class="params">(<span class="keyword">int</span> newWidth, <span class="keyword">int</span> newHeight, <span class="keyword">int</span> oldWidth, <span class="keyword">int</span> oldHeight)</span> </span>&#123;</div><div class="line"> 	<span class="comment">//调用onSizeChanged方法，这个方法是空的；如果有操作需要在尺寸发生变化时，可以重写这个方法</span></div><div class="line">	onSizeChanged(newWidth, newHeight, oldWidth, oldHeight);</div><div class="line">	<span class="keyword">if</span> (mOverlay != <span class="keyword">null</span>) &#123;</div><div class="line">  	  mOverlay.getOverlayView().setRight(newWidth);</div><div class="line">   	 mOverlay.getOverlayView().setBottom(newHeight);</div><div class="line">   &#125;</div><div class="line">   rebuildOutline();</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>上面代码没有什么难度，在setFrame方法里根据新边距和旧边距，判断尺寸是否发生变化，如果变化就去调用sizeChange方法，onSizeChanged就是在sizeChange中调用的。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Android/" rel="tag"># Android</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/01/21/Android-View的测量/" rel="next" title="Android View的测量">
                <i class="fa fa-chevron-left"></i> Android View的测量
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/01/21/回调机制的个人理解/" rel="prev" title="回调机制的个人理解">
                回调机制的个人理解 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>

          
          </div>
          


          
  <div class="comments" id="comments">
    
      <div class="ds-thread" data-thread-key="2017/01/21/Android-View的布局过程/"
           data-title="Android View的布局过程" data-url="https://www.yanhaoblog.com/2017/01/21/Android-View的布局过程/">
      </div>
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel sidebar-panel-active">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/demo.png"
               alt="闫浩" />
          <p class="site-author-name" itemprop="name">闫浩</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
        
          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">14</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">5</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
        </div>

        
        

        
        

        


      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">闫浩</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>


<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>

<div class="powered-by">
Hosted by <a href="https://pages.coding.me" style="font-weight: bold">Coding Pages</a>
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>



        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"yanhaods"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    
    <script src="/lib/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  












  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
